/**
 * 
 */
package net.yters.model.agents.actuators.sensors;

import java.util.ArrayList;

import net.yters.util.Box;
import net.yters.util.Util;

public class ClosestAgentOfTypeSensor extends SensorAgent {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6965989663214104569L;
	ArrayList<Box> f_types = null;

	Box f_obs_distance = new Box(new Double(0));
	Box f_obs_angle = new Box(new Double(0));
	Box f_obs_agent_hp = new Box(new Double(0));

	public ClosestAgentOfTypeSensor (ArrayList<Box> types) {
		f_types = types;

		addBoxedObservation("distance", f_obs_distance);
		addBoxedObservation("angle", f_obs_angle);
		addBoxedObservation("agent_hp", f_obs_agent_hp);

		f_state.putAll(f_observations);
	}

	@Override
	public void execute() {
		double oldDistance = Double.NaN;
		double newDistance = Double.NaN;
		double angle = Double.NaN;
		double hp = Double.NaN;

		f_obs_distance.f_value = newDistance;
		f_obs_angle.f_value = angle;
		f_obs_agent_hp.f_value = hp;

		for(Box type : f_types) {
			ArrayList<Double> input = Util.closestAgentByType(f_ownerAgent, f_ownerAgent.f_model.f_agents, (Double) type.f_value);

			newDistance = input.get(0);
			angle = input.get(1);
			hp = input.get(2);

			if(oldDistance > newDistance || Double.isNaN(oldDistance)) { // TODO HACK should be handled more elegantly
				oldDistance = newDistance;
				f_obs_distance.f_value = newDistance;
				f_obs_angle.f_value = angle;
				f_obs_agent_hp.f_value = hp;
			}
		}
	}
}